SaveData["episode"] = SaveData["episode"] or {}

--local bosshpHUD = require("Libraries.BossHP")
--bosshpHUD.addBossID(39, -1, 3)

local hasGenerated = false
local hasTransformed = false --if we've transformed an egg or not
local ran
local frameCount = 1
local totalamountofegg = 1 -- used to guarantee an egg for the first shot, and a fireball on the second shot, just to teach the player "oh hey this is a thing"

-- the original code was terribly indented, what the hell :v

local ChangedHealth = false

function onTick()
	--Text.print(totalamountofegg, 20, 220)
	tableOfBirdo = NPC.get(39, -1)
	tableOfBirdoEggs = NPC.get(40, -1)
	if (tableOfBirdo[1] ~= nil) then
		if globalsave.HardMode and not ChangedHealth and tableOfBirdo[1]:mem(0x148, FIELD_FLOAT) == -2 then
			-- change health in hard mode; gotta use this janky work around since hit points aren't initialized until the boss actually loads?
			ChangedHealth = true
			tableOfBirdo[1]:mem(0x148, FIELD_FLOAT, -3)
		end
		if(tonumber(tableOfBirdo[1]:mem(0xF0, FIELD_DFLOAT)) == 1)
		and (tonumber(tableOfBirdo[1]:mem(0xF0, FIELD_DFLOAT)) == 1) then
			frameCount = frameCount + 1
			if not hasGenerated then
				ran = RNG.randomInt(0, 2)
				hasGenerated = true
			end
			if (((ran == 2) and (frameCount > 21)) and totalamountofegg > 2)
			or ((frameCount > 21) and (totalamountofegg == 2)) then
				if (table.getn(tableOfBirdoEggs) > 0) then
					tableOfBirdoEggs = NPC.get(40, -1) --update table
					if (hasTransformed == false) then
						tableOfBirdoEggs[table.getn(tableOfBirdoEggs)]:mem(0xE2, FIELD_WORD, 282) --modification
						playSFX(42) --big fireball
						hasTransformed = true --so we don't re-transform anything else
					end
					if totalamountofegg == 2 then
						totalamountofegg = 3
					end
				end
			elseif (totalamountofegg == 1 and (frameCount > 21)) or (tonumber(tableOfBirdo[1]:mem(0xF8, FIELD_DFLOAT)) == 280) then
				if (totalamountofegg == 1 and (frameCount > 21)) then totalamountofegg = 2 end
				hasGenerated = false --just reset everything
				hasTransformed = false
				frameCount = 0
			end
		end
	end
end

-- On Birdo's death, save SaveData in the save file, and spawn the star.. 
function onNPCKill(eventObj, npcObj, npcKillReason) 
	if npcObj.id == 39 and npcKillReason == 3 then 
		globalsave.DefeatBirdo = true
		NPC.spawn(97, npcObj.x, npcObj.y, npcObj.section)
	elseif npcObj.id == 97 and npcKillReason == 9 then
		Text.showMessageBox("A new pipe has appeared outside Peach's Castle!")
	end
end